<template>
  <div class="foreign-favorites-page">
    <h2>国外菜谱收藏</h2>
    <el-row justify="end" style="margin-bottom: 16px;">
      <el-button type="primary" @click="fetchFavorites">刷新</el-button>
    </el-row>
    <el-table
      :data="favorites"
      stripe
      border
      style="width: 100%"
    >
      <el-table-column prop="recipeImg" label="图片" width="120">
        <template #default="{ row }">
          <el-image :src="row.recipeImg" style="width: 80px; height: 80px; object-fit: cover;" />
        </template>
      </el-table-column>
      <el-table-column prop="cookbName" label="菜谱名" />
      <el-table-column prop="cuisine" label="菜系" width="120" />
      <el-table-column prop="place" label="地区" width="120" />
      <el-table-column prop="tags" label="标签" width="150">
        <template #default="{ row }">
          <el-tag v-if="row.tags" size="small" style="margin-right: 4px;">{{ row.tags }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="showDetail(row.id)">详情</el-button>
          <el-button size="small" type="danger" @click="removeFavorite(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      width="70%"
      :title="selected?.cookbName || '详情'"
    >
      <div v-if="selected" class="recipe-detail">
        <div class="recipe-header">
          <el-image
            :src="selected.recipeImg"
            fit="cover"
            style="width: 100%; height: 300px; margin-bottom: 16px; border-radius: 8px;"
          />
          <div class="recipe-info">
            <h3>{{ selected.cookbName }}</h3>
            <div class="recipe-meta">
              <el-tag>{{ selected.cuisine }}</el-tag>
              <el-tag type="success" style="margin-left: 8px;">{{ selected.place }}</el-tag>
              <el-tag type="warning" v-if="selected.tags" style="margin-left: 8px;">{{ selected.tags }}</el-tag>
            </div>
          </div>
        </div>

        <el-divider>食材清单</el-divider>
        <div class="ingredients-list">
          <el-row :gutter="20">
            <el-col :span="12" v-for="(ingredient, index) in selected.ingredients" :key="index">
              <div class="ingredient-item">
                <span class="measure">{{ ingredient.measure }}</span>
                <span class="name">{{ ingredient.name }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <el-divider>烹饪步骤</el-divider>
        <div class="instructions">
          <p style="white-space: pre-wrap;">{{ selected.content }}</p>
        </div>

        <div v-if="selected.youtube" class="youtube-link">
          <el-divider>视频教程</el-divider>
          <el-link type="primary" :href="selected.youtube" target="_blank">
            <el-icon><VideoPlay /></el-icon>
            观看视频教程
          </el-link>
        </div>
      </div>
      <template #footer>
        <el-button text @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useUserStore } from '@/store/islogin'
import axios from 'axios'
import { getFgFavoriteApi} from '@/api/fgRecipe/index'
import { VideoPlay } from '@element-plus/icons-vue'
import http from '@/http'
import { ElMessage } from 'element-plus'

interface Ingredient {
  name: string
  measure: string
}

interface ForeignFavorite {
  favoriteId: string
  id: string
  cookbName: string
  cuisine: string
  place: string
  content: string
  recipeImg: string
  tags: string | null
  youtube: string | null
  ingredients: Ingredient[]
}

const useUser = useUserStore()
const userId = ref()

const favorites = ref<ForeignFavorite[]>([])
const dialogVisible = ref(false)
const selected = ref<ForeignFavorite | null>(null)

onMounted(() => {
    fetchFavorites()
})

/**
 * 获取收藏的 recipeId 列表，然后调用 TheMealDB 接口获取详情
 */
const fetchFavorites = async (): Promise<void> => {
  // 0. 确保拿到当前登录用户的 ID
  if (useUser.user) {
    userId.value = useUser.user.userId
  }
  // 1. 调用后端接口，传入 userId 获取该用户收藏的 recipeId 数组
  const res = await getFgFavoriteApi(userId.value)
  const recipeIds: string[] = res.data || []

  // 2. 并行向 TheMealDB 查询每个 recipeId 的菜谱详情
  const details = await Promise.all(
    recipeIds.map(id =>
      axios
        .get(`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${id}`)
        .then(resp => resp.data.meals?.[0])
    )
  )
  // 3. 把获取到的原始接口数据，转换成前端需要的 favorites 数据结构
  favorites.value = details
    // 3.1 过滤掉任何未找到的菜谱（可能接口没返回数据）
    .filter((meal): meal is any => Boolean(meal))
    // 3.2 遍历有效的菜谱对象，映射成我们定义的 ForeignFavorite 结构
    .map(meal => {
      // 3.2.1 动态提取最多 20 组 “原料+用量”
      const ingredients: Ingredient[] = []
      for (let i = 1; i <= 20; i++) {
        const ingredient = meal[`strIngredient${i}`]
        const measure    = meal[`strMeasure${i}`]
        if (ingredient && ingredient.trim()) {
          ingredients.push({
            name:    ingredient,
            measure: measure || ''
          })
        }
      }
      // 3.2.2 返回完整的前端显示对象
      return {
        favoriteId:  meal.idMeal,           // 用作唯一标识
        id:          meal.idMeal,           // 同上，可用于查询细节
        cookbName:   meal.strMeal,          // 菜名
        cuisine:     meal.strCategory,      // 分类
        place:       meal.strArea,          // 地区
        content:     meal.strInstructions,  // 做法
        recipeImg:   meal.strMealThumb,     // 缩略图
        tags:        meal.strTags,          // 标签（逗号分隔）
        youtube:     meal.strYoutube,       // 视频链接
        ingredients                     // 上面组装的原料用量数组
      }
    })
}

const deletable = reactive({
  userId:'',
  fgreId:''
})
const deleRecipe =(parm:any)=>{
    return http.post("/api/fg/delete",parm)
}
/** 显示详情 */
const showDetail = (id: string): void => {
  selected.value = favorites.value.find(f => f.id === id) || null
  dialogVisible.value = true
}

/** 删除收藏 */
const removeFavorite = async (recipeId: string) => {
  console.log(recipeId)
  if(useUser.user){
    deletable.userId=useUser.user.userId
    deletable.fgreId=recipeId
    const res = await deleRecipe(deletable)
    if(res.code==200){
      ElMessage.success(res.msg)
      fetchFavorites()
    }

  }
}
</script>

<style scoped>
.foreign-favorites-page {
  padding: 20px;
  background: #fff;
}

.recipe-detail {
  padding: 0 20px;
}

.recipe-header {
  margin-bottom: 24px;
}

.recipe-info {
  margin-top: 16px;
}

.recipe-meta {
  margin-top: 12px;
}

.ingredients-list {
  margin: 16px 0;
}

.ingredient-item {
  padding: 8px;
  border-bottom: 1px solid #eee;
}

.ingredient-item .measure {
  color: #666;
  margin-right: 8px;
}

.instructions {
  line-height: 1.6;
  color: #333;
}

.youtube-link {
  margin-top: 24px;
  text-align: center;
}
</style>